//
//  InfoViewController.m
//  MyLittleBrother
//
//  Created by speeda on 17/8/3.
//  Copyright © 2017年 speeda. All rights reserved.
//

#import "DetailsViewController.h"
#import "ArticleModel.h"
#import <SDWebImage/UIButton+WebCache.h>
#import "CommentModel.h"
#import "LLPhotoCell.h"
#import "DetailCell.h"
#import "LLPhotoBrowser.h"
#import "YZInputView.h"
#import "UITextView+YZEmotion.h"
#import "YZTextAttachment.h"

@interface DetailsViewController () <UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,LLPhotoBrowserDelegate,UITextViewDelegate,UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIButton *headButton;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

@property (weak, nonatomic) IBOutlet UICollectionView *imgsCollectionView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imgsCollectionHeight;
@property (nonatomic, strong) NSArray *imgsArray;

@property (weak, nonatomic) IBOutlet UILabel *boxNumLabel;
@property (weak, nonatomic) IBOutlet UICollectionView *boxCollectionView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *boxCollectionHeight;

@property (weak, nonatomic) IBOutlet UILabel *comentNumLabel;
@property (weak, nonatomic) IBOutlet UIView *bottomView;

@property (weak, nonatomic) IBOutlet UITableView *detailTableView;

@property (nonatomic, strong) NSArray *boxArray;

@property (nonatomic, strong) NSMutableArray *commentArray;

@property (nonatomic, strong) ArticleModel *articleItem;
@property (weak, nonatomic) IBOutlet UIView *commentView;
@property (weak, nonatomic) IBOutlet YZInputView *commentTextView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomHCons;

@property (weak, nonatomic) IBOutlet UIView *tableViewHeadView;

@property (nonatomic, strong) NSString *re_userid;

@property (strong, nonatomic) YZEmotionKeyboard *emotionKeyboard;

@end

@implementation DetailsViewController

static NSString *reuseIdentifier = @"reuseIdentifier";


// 懒加载键盘
- (YZEmotionKeyboard *)emotionKeyboard
{
    // 创建表情键盘
    if (_emotionKeyboard == nil) {
        __weak typeof(self) weakSelf = self;
        YZEmotionKeyboard *emotionKeyboard = [YZEmotionKeyboard emotionKeyboard];
        emotionKeyboard.sendContent = ^(NSString *content){
            // 点击发送会调用，自动把文本框内容返回给你
            [weakSelf requestGetcode:content];
            [weakSelf.commentTextView resignFirstResponder];
            weakSelf.commentView.hidden = YES;
        };
        
        _emotionKeyboard = emotionKeyboard;
    }
    return _emotionKeyboard;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"详情";
    
//    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self setNavigationItem];
    
    [self initView];

    [self requestGetarticle];
    
}


- (void)setNavigationItem {
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn addTarget:self action:@selector(rightBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setImage:[UIImage imageNamed:@"btn_more"] forState:UIControlStateNormal];
    [rightBtn sizeToFit];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightBarItem;
}

- (void)rightBtnAction {
    
    //初始化提示框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"分享" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
    
}

- (void)initView {

    _commentView.layer.borderWidth = 1;
    _commentView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _commentTextView.layer.cornerRadius = 5;
    _commentTextView.layer.borderWidth = 1;
    _commentTextView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _commentTextView.delegate = self;
    // 设置文本框占位文字
    _commentTextView.placeholderColor = [UIColor lightGrayColor];
//    _commentTextView.inputAccessoryView = [[UIView alloc] init];
    
    // 监听文本框文字高度改变
    _commentTextView.yz_textHeightChangeBlock = ^(NSString *text,CGFloat textHeight){
        // 文本框文字高度改变会自动执行这个【block】，可以在这【修改底部View的高度】
        // 设置底部条的高度 = 文字高度 + textView距离上下间距约束
        // 为什么添加10 ？（10 = 底部View距离上（5）底部View距离下（5）间距总和）
        _bottomHCons.constant = textHeight + 20;
    };
    
    // 设置文本框最大行数
    _commentTextView.maxNumberOfLines = 4;
    
}

- (void)initTableView {
    
    self.detailTableView.dataSource = self;
    self.detailTableView.delegate = self;
    self.detailTableView.estimatedRowHeight = 100;
    self.detailTableView.rowHeight = UITableViewAutomaticDimension;
    self.detailTableView.tableFooterView = [[UIView alloc] init];
}

- (void)initImgsCollectionView {
        
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(SCREEN_WIDTH, 200);
    layout.minimumLineSpacing = 5;
    self.imgsCollectionView.collectionViewLayout = layout;
    self.imgsCollectionView.scrollEnabled = NO;
    self.imgsCollectionView.dataSource = self;
    self.imgsCollectionView.delegate = self;
    //注册cell
    [self.imgsCollectionView registerClass:[LLPhotoCell class] forCellWithReuseIdentifier:reuseIdentifier];
}

- (void)initBoxCollectionView {

    UICollectionViewFlowLayout *boxLayout = [[UICollectionViewFlowLayout alloc] init];
    boxLayout.itemSize = CGSizeMake(40, 40);
    self.boxCollectionView.collectionViewLayout = boxLayout;
    boxLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    boxLayout.minimumLineSpacing = 10;
    //    boxLayout.minimumInteritemSpacing = 10;
    self.boxCollectionView.dataSource = self;
    self.boxCollectionView.delegate = self;
    //注册cell
    [self.boxCollectionView registerClass:[LLPhotoCell class] forCellWithReuseIdentifier:reuseIdentifier];
}




#pragma mark -- 送盒子
- (IBAction)giveBoxBtnAction:(id)sender {
    
    
}


#pragma mark -- 评论
- (IBAction)messageBtnAction:(id)sender {
    
    self.re_userid = nil;
    self.commentView.hidden = NO;
    self.commentTextView.placeholder = @"评论";
    [self.commentTextView becomeFirstResponder];
}


// 表情键盘button
- (IBAction)clickEmojiBtnBtn:(UIButton *)sender{
    
    if (_commentTextView.inputView == nil) {
        _commentTextView.yz_emotionKeyboard = self.emotionKeyboard;
        [sender setImage:[UIImage imageNamed:@"toolbar-text"] forState:UIControlStateNormal];
    } else {
        _commentTextView.inputView = nil;
        [_commentTextView reloadInputViews];
        [sender setImage:[UIImage imageNamed:@"smail"] forState:UIControlStateNormal];
    }

}


#pragma mark -- 获取贴子详情
- (void)requestGetarticle {
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"command"] = @"getarticle";
    dict[@"topicid"] = @"";
    dict[@"circleid"] = self.circleid;
    dict[@"page"] = @"";
    
    [AFHTTPSTool POSTRequestRequestWebsite:Url AndDictionary:dict success:^(NSURLSessionDataTask *dataTask, id responseObject) {
        
        NSDictionary *dic = responseObject;
        NSString *state = [NSString stringWithFormat:@"%@",dic[@"code"]];
        if ([state isEqualToString:@"000000"]) {
            
            NSLog(@"获取贴子详情 = %@",responseObject);
            NSArray *rows = [dic[@"data"] objectForKey:@"rows"];
            
            ArticleModel *articleItem = [ArticleModel mj_objectWithKeyValues:rows.firstObject];
            [self.headButton sd_setBackgroundImageWithURL:[NSURL URLWithString:articleItem.b_headimg] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"img_touxiang"]];
            self.nameLabel.text = articleItem.b_nickname;
            self.timeLabel.text = [NSString timeWithTimeIntervalString:articleItem.b_ctime];
            NSMutableAttributedString *attrStr = [Utility emotionStrWithString:[NSString stringWithFormat:@"%@\n",articleItem.b_article] plistName:@"emoticons.plist" y:-5];
            self.titleLabel.attributedText = attrStr;
            self.boxNumLabel.text = [NSString stringWithFormat:@"%@ 盒子",articleItem.b_box_sum];
            self.comentNumLabel.text = [NSString stringWithFormat:@"%@ 评论",articleItem.b_comments_sum];
            
            
            if (articleItem.b_imgs.length) {
                
                self.imgsArray = [articleItem.b_imgs componentsSeparatedByString:@"|"];
                
                self.imgsCollectionHeight.constant = self.imgsArray.count * 205;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self initImgsCollectionView];
                });
                
            } else {
            
                self.imgsCollectionHeight.constant = 0;
            }
            
            if (articleItem.b_box_sum.integerValue > 0) {
                
                self.boxCollectionHeight.constant = 50;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self initBoxCollectionView];
                });
                
            } else {
            
                self.boxCollectionHeight.constant = 0;
            }
            
            CGSize titleSize = [articleItem.b_article boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 40, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:16]} context:nil].size;
            
            self.tableViewHeadView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.imgsCollectionHeight.constant + 170 + titleSize.height + self.boxCollectionHeight.constant);
            
            self.commentArray = [CommentModel mj_objectArrayWithKeyValuesArray:articleItem.comment];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self initTableView];
            });
            

        } else {
            
            NSString *errorText = [NSString stringWithFormat:@"%@",dic[@"msg"]];
            [SVProgressHUD showInfoWithStatus:errorText];
        }
        
        
    } failure:^(NSURLSessionDataTask *dataTask, NSError *error) {
        
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }];
}



#pragma mark -- 评论
- (void)requestGetcode:(NSString *)text {
    
    NSString *userid = [[NSUserDefaults standardUserDefaults] objectForKey:kUserid];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"command"] = @"comment";
    dict[@"userid"] = userid;
    dict[@"re_userid"] = self.re_userid;
    dict[@"circleid"] = self.circleid;
    dict[@"comment"] = text;
    
    [AFHTTPSTool POSTRequestRequestWebsite:Url AndDictionary:dict success:^(NSURLSessionDataTask *dataTask, id responseObject) {
        
        NSDictionary *dic = responseObject;
        NSString *state = [NSString stringWithFormat:@"%@",dic[@"code"]];
        if ([state isEqualToString:@"000000"]) {
            
            NSLog(@"评论 = %@",responseObject);
            self.commentTextView.text = @"";
            
            NSInteger integer = self.comentNumLabel.text.integerValue;
            self.comentNumLabel.text = [NSString stringWithFormat:@"%zd 评论",++integer];
        
            NSString *nickname = [[NSUserDefaults standardUserDefaults] objectForKey:kNickname];
            NSString *headimg = [[NSUserDefaults standardUserDefaults] objectForKey:kHeadimg];
            //获取当地时间
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSDate *datenow = [NSDate date];
            NSString *dateTime = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
      
            CommentModel *commrntItem = [[CommentModel alloc] init];
            commrntItem.b_headimg = headimg;
            commrntItem.b_nickname = nickname;
            commrntItem.b_comment = text;
            commrntItem.b_retime = dateTime;
            commrntItem.b_re_userid = self.re_userid;
            [self.commentArray addObject:commrntItem];
            
            [self.detailTableView reloadData];
            
        } else {
            
            NSString *errorText = [NSString stringWithFormat:@"%@",dic[@"msg"]];
            [SVProgressHUD showInfoWithStatus:errorText];
        }
        
        
    } failure:^(NSURLSessionDataTask *dataTask, NSError *error) {
        
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }];
}


#pragma maek -- UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.commentArray.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellID = @"cellID";
    DetailCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"DetailCell" owner:nil options:nil];
        cell = [nibs lastObject];
    }
    
    CommentModel *commentItem = self.commentArray[indexPath.row];
    
    [cell.headImageView sd_setImageWithURL:[NSURL URLWithString:commentItem.b_headimg] placeholderImage:[UIImage imageNamed:@"img_touxiang"]];
    
    NSDictionary *dict = @{NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName:[UIFont fontWithName:@"Helvetica-Bold" size:14]};
    
    NSMutableAttributedString *str = nil;
    if (commentItem.b_re_nickname != NULL) {
        str = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@回复%@：",commentItem.b_nickname,commentItem.b_re_nickname]];
        [str addAttributes:dict range:NSMakeRange(commentItem.b_nickname.length + 2, commentItem.b_re_nickname.length)];
    } else {
        
        str = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@：",commentItem.b_nickname]];
    }
    [str addAttributes:dict range:NSMakeRange(0, commentItem.b_nickname.length)];
    
    cell.nameLabel.attributedText = str;
    NSMutableAttributedString *comment = [Utility emotionStrWithString:commentItem.b_comment plistName:@"emoticons.plist" y:-5];
    cell.subTextLabel.attributedText = comment;
    cell.timeLabel.text = [NSString timeWithTimeIntervalString:commentItem.b_retime];
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CommentModel *commentItem = self.commentArray[indexPath.row];
    self.re_userid = commentItem.b_id;
    self.commentView.hidden = NO;
    [self.commentTextView becomeFirstResponder];
    self.commentTextView.placeholder = [NSString stringWithFormat:@"回复%@：",commentItem.b_re_nickname];
}


#pragma mark -- UICollectionViewDataSource,UICollectionViewDelegate
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    NSInteger count = 0;
    if (collectionView == self.imgsCollectionView) {
        
        count = self.imgsArray.count;
        
    } else {
    
        count = self.commentArray.count;
    }
    
    return count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    LLPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    if (collectionView == self.imgsCollectionView) {
        
        [cell.bigImgV sd_setImageWithURL:[NSURL URLWithString:self.imgsArray[indexPath.row] ] placeholderImage:[UIImage imageNamed:@"bg_taren"]];
        
    } else {
        
        CommentModel *comentItem = self.commentArray[indexPath.row];
        UIImageView *imageView = [[UIImageView alloc]init];
        [imageView sd_setImageWithURL:[NSURL URLWithString:comentItem.b_headimg] placeholderImage:[UIImage imageNamed:@"bg_taren"]];
        imageView.layer.cornerRadius = cell.frame.size.width * 0.5;
        imageView.layer.masksToBounds = YES;
        cell.backgroundView = imageView;
    }
    
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (collectionView == self.imgsCollectionView) {
        
    // 1 初始化
    LLPhotoBrowser *photoBrowser = [[LLPhotoBrowser alloc]init];
    // 2 设置代理
    photoBrowser.delegate = self;
    // 3 设置当前图片
    photoBrowser.currentImageIndex = indexPath.item;
    // 4 设置图片的个数
    photoBrowser.imageCount = self.imgsArray.count;
    // 5 设置图片的容器
    photoBrowser.sourceImagesContainerView = self.imgsCollectionView;
    // 6 展示
    [photoBrowser show];
        
    }
    
}

//// 代理方法 返回图片URL
- (NSURL *)photoBrowser:(LLPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index{
    
    NSURL *url = [NSURL URLWithString:self.imgsArray[index]];
    
    return url;
}
// 代理方法返回缩略图
- (UIImage *)photoBrowser:(LLPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index{
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    
    LLPhotoCell *cell = (LLPhotoCell *)[self.imgsCollectionView cellForItemAtIndexPath:indexPath];
    
    return cell.bigImgV.image;
    
}



#pragma mark -- UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

    if ([text isEqualToString:@"\n"]) {
        [self requestGetcode:[self emotionText]];
        [self.commentTextView resignFirstResponder];
        self.commentView.hidden = YES;
        return NO;
    }
    
    return YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    [self.commentTextView resignFirstResponder];
    self.commentView.hidden = YES;
}

// 获取表情字符串
- (NSString *)emotionText
{
    
    NSMutableString *strM = [NSMutableString string];
    
    [_commentTextView.attributedText enumerateAttributesInRange:NSMakeRange(0, _commentTextView.attributedText.length) options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
        NSString *str = nil;
        
        YZTextAttachment *attachment = attrs[@"NSAttachment"];
        
        if (attachment) { // 表情
            str = attachment.emotionStr;
            [strM appendString:str];
        } else { // 文字
            str = [_commentTextView.attributedText.string substringWithRange:range];
            [strM appendString:str];
        }
        
    }];
    return strM;
}


- (NSMutableArray *)commentArray {
    
    if (!_commentArray) {
        _commentArray = [NSMutableArray array];
    }
    
    return _commentArray;
}

@end
